<template>
  <view class="category">
    <view class="tab">
      <uni-segmented-control :current="current" :values="tabs.map(v=>v.title)" @clickItem="onClickItem" style-type="text" active-color="#d4237a">
      </uni-segmented-control>
    </view>
    <scroll-view class="category-content" enable-flex scroll-y :scroll-top="scrollTop" @scrolltolower='handleToLower'>
      <view class="category-item" v-for="v in vertical" :key='v.id'>
        <image :src="v.thumb" mode="widthFix" />
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { uniSegmentedControl } from '@dcloudio/uni-ui'
export default {
  components: { uniSegmentedControl },
  props: {},
  data() {
    return {
      params: {
        order: 'new',
        limit: 30,
        skip: 0
      },
      id: '0',
      tabs: [
        { order: 'new', title: '最新' },
        {
          order: 'hot',
          title: '热门'
        }
      ],
      vertical: [],
      htmlCache: {},
      scrollTop: 0
    }
  },
  onLoad(option) {
    this.id = option.id
    // this.id = '4e4d610cdf714d2966000002'
    this.loadVertical()
  },
  methods: {
    async loadVertical() {
      const { res } = await this.request({ url: `/image/v1/vertical/category/${this.id}/vertical`, data: this.params })
      if (res.vertical.length === 0) {
        this.hasMore = false
        uni.showToast({ title: '没有更多数据了', icon: 'none' })
        return
      }
      this.vertical.push(...res.vertical)
      this.htmlCache[this.params.order] = this.vertical
    },
    handleToLower() {
      if (this.hasMore) {
        this.params.skip += this.params.limit
        this.loadVertical()
      } else {
        uni.showToast({ title: '没有更多数据了', icon: 'none' })
      }
    },
    onClickItem(e) {
      if (this.current !== e.currentIndex) {
        this.current = e.currentIndex
        this.params.skip = 0
        const key = this.tabs[this.current].order
        this.params.order = key
        this.scrollTop = 0
        if (!this.htmlCache[key]) {
          this.vertical = []
          this.loadVertical()
        } else {
          this.vertical = this.htmlCache[key]
        }
      }
    }
  }
}
</script>

<style  lang='scss' scoped>
.tab {
  width: 50%;
  margin: 0 auto;
}
.category-content {
  height: calc(100vh - 36px);
  display: flex;
  flex-wrap: wrap;
  .category-item {
    width: 33.33%;
    border: 5rpx solid #fff;
  }
}
</style>